<?php
namespace app\common\service\product;

use app\common\model\product\Product;
use app\common\model\product\ProductConfig;
use think\facade\Db;

use app\common\library\wechat\WxQrcode;
/**
 * 分享图合成处理
 * Class ShareMapService
 * @package app\common\service\product
 */
class ShareMapService
{
    public $fileDir = '';

    public $typefaceColor;
    
    
    public function productShareImg($productId){

        $productModel = Product::where('id', $productId)->find();
        $code_image = $productModel->code_image;
        $cover = $productModel->cover;
        if (!$code_image) {
            $code_image = $this->openCode($productId);
        }
        $imgUrl = ProductConfig::where('store_id', $productModel->store_id)->value('product_img');
        $storeName = Db::table('evt_mini_room_list')->where('id', $productModel->store_id)->value('room_name');

        //$imgUrl = 'http://imagev3.dzxwbj.com/temp/20221027/35b843a40e62456b8ba52413fefa7ffe.png';
        //背景图
        if (empty($imgUrl)) {
            return [];
        }

        $background = explode('.com/', $imgUrl)[1];
        $dir = dirname(dirname(dirname(dirname(dirname(__FILE__))))).'/public/uploads/';
        $this->setDir($dir);
        //$imageBackground = $this->imgCircularHandle($background, false);                  //图片变圆处理

        $imageBackground = $this->radius_img($background,1);  //背景图

        //$imageBackground = $this->getImgResource($background,false);  //背景图
        $backgroundWide = imagesx($imageBackground);
        $backgroundHigh = imagesy($imageBackground);
        $image = $this->createImgDrawingBoard($backgroundWide, $backgroundHigh); //绘制图像资源
        //导入背景图
        $this->twoImgComposeHandle($image,$imageBackground,0,0,0,0,$backgroundWide,$backgroundHigh,$backgroundWide,$backgroundHigh);



        //展示图片导入【商品图】
        list($shWide,$shHigh) = [48,118];  //位置
        list($showWide,$showHigh) = [658,630]; //图大小
        //http://imagev3.dzxwbj.com/temp/20220929/22928c1a23d1d7aa1f9f99e4ab583aa5.png
        $showUrl = $dir.explode('.com/', $cover)[1];
        $showImage = $this->getImgResource($showUrl,true);
        if($showWide == imagesx($showImage)  &&  $showHigh == imagesy($showImage)) {
            $imageShowImg = $showImage;
        } else {
            $imageShowImg = $this->createImgDrawingBoard($showWide, $showHigh);
            $this->twoImgComposeHandle($imageShowImg,$showImage,0,0,0,0,$showWide,$showHigh,imagesx($showImage),imagesy($showImage));
        }
        $this->imageCopyHandle($image, $imageShowImg, $shWide, $shHigh, 0, 0, $showWide, $showHigh);

        //导入菊花码
        //http://imagev3.dzxwbj.com/temp/20220929/d2c7f63ad181cb18ffa4ac559c620a76.png
        $qrUrl = $dir.explode('.com/', $code_image)[1];
        $originalImageQr = $this->getImgResource($qrUrl,true);
        $originalQrWide = imagesx($originalImageQr);
        $originalQrHigh = imagesy($originalImageQr);

        list($qrWide,$qrHigh) = [164,164];
        list($qrCodeX,$qrCodeY) = [542,844];
        $imageQr= $this->createImgDrawingBoard($originalQrWide, $originalQrHigh);
        $this->twoImgComposeHandle($imageQr,$originalImageQr,0,0,0,0,$qrWide,$qrHigh,$originalQrWide,$originalQrHigh);
        $this->imageCopyHandle($image, $imageQr,$qrCodeX,$qrCodeY, 0,0, $qrWide, $qrHigh);

        //文字导入 --- 商品标题
        $name = '长按识别二维码';
        $this->setTypefaceImageColor($image,110,124,137);
        list($titleX,$titleY) = [520,1065];
        $this->imageTtfTextHandle($image,22,0, $titleX,$titleY, $name);

        //门店
        //$storeName = '青柠茶室门店';
        $this->setTypefaceImageColor($image,225,225,225);
        $nameLen = strlen($storeName)/4 * 48 + ((strlen($storeName)/4 -1) *1);
        $titleX = $backgroundWide/2 - $nameLen/2;
        $titleY = 70;
        $this->imageTtfTextHandle($image,30,0, $titleX,$titleY, $storeName);

        //商品标题
        $shopName = $productModel->name;
        $this->setTypefaceImageColor($image,37,58,78);
        $title_size = 33;
        $title_row = 65; //行距
        $title_line_num = 9; //多少字换行
       // list($titleX,$titleY) = [24,439];
        list($titleX,$titleY) = [48,878];
        $shopNameLen =mb_strlen($shopName,'UTF8');
        if($shopNameLen > $title_line_num && $title_line_num > 0) { //进行换行处理
            $shopNameOne = mb_substr($shopName,0,$title_line_num,'UTF8');
            $shopNameTow = mb_substr($shopName,$title_line_num,$title_line_num,'UTF8');
            $this->imageTtfTextHandle($image,$title_size,0, $titleX,$titleY, $shopNameOne);
            $this->imageTtfTextHandle($image,$title_size,0, $titleX,$titleY+$title_row, $shopNameTow);
        }else {
            $this->imageTtfTextHandle($image,$title_size,0, $titleX,$titleY, $shopName);
        }

        //价格
        $price = '￥';
        $this->setTypefaceImageColor($image,243,93,81);
        //list($titleX,$titleY) = [24,525];
        list($titleX,$titleY) = [48,1065];
        $this->imageTtfTextHandle($image,23,0, $titleX,$titleY, $price);
        $price = $productModel->price*1;
        $this->setTypefaceImageColor($image,243,93,81);
        //list($titleX,$titleY) = [38,525];
        list($titleX,$titleY) = [76,1065];
        $this->imageTtfTextHandle($image,35,0, $titleX,$titleY, $price);

        $price = '原价¥'.$productModel->market_price*1;
        $this->setTypefaceImageColor($image,158,168,177);
        //list($titleX,$titleY) = [85,525];
        list($titleX,$titleY) = [170,1065];
        $this->imageTtfTextHandle($image,22,0, $titleX,$titleY, $price);

        $catalogRoute = $this->getDir().'temp/share';
        $imgName = $productId.'_'.$productModel->store_id.'_'.time();
        $this->generateImageSave($image, $catalogRoute, $imgName);     //合成图片存储


        // https://csnum13.dzxwbj.com/uploads
        $url = 'https://csnum13.dzxwbj.com/uploads/temp/share/'.$imgName.'.png';
        return $url;
        //$this->imageDisplay($image);die;
    }
    
    
    public function openCode($productId)
    {
        $product = Db::table('evt_customer_product')->where('id', $productId)->find();
        $id = $productId;
        $sort_id = $product['store_id'];
        $roomInfo = Db::table('evt_mini_room_list')->where('id', $sort_id)->find();
        $wxapp = Db::table('evt_mini_match')->where('wxapp_id', '=', $roomInfo['admin_id'])->find();


        $qrCode = new WxQrcode([
            'app_id' => $wxapp['app_id'],
            'app_secret' => $wxapp['key'],
        ]);

        $img = $id.'_'.'_'.$sort_id.'_'.$roomInfo['admin_id'].'.png';
        $file_path = 'qrcode/' .$sort_id.'_'.$roomInfo['admin_id'] . '/product/';
        $path = root_path() . 'public/uploads/' . $file_path;
        if (!file_exists($path)) {
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
            mkdir($path, 0777, true);
        }
        $filename = $path . $img;

        $info = $qrCode->getQrcode($filename,'s='.$roomInfo['admin_id'].'&m='.$sort_id.'&g='.$id,'pages2/market/detail');
        $imgs = '';
        if($info) {
            $imgs = get_image_url('/' . $file_path.$img);
            $rowId = Db::table('evt_customer_product')->where('id', $id)->update([
                'code_image' => $imgs
            ]);
        }

        return $imgs;
    }


    public function productShareImgOld($productId){

        $productModel = Product::where('id', $productId)->find();
        $code_image = $productModel->code_image;
        $cover = $productModel->cover;
        $imgUrl = ProductConfig::where('store_id', $productModel->store_id)->value('product_img');
        $storeName = Db::table('evt_mini_room_list')->where('id', $productModel->store_id)->value('room_name');

        //背景图
        if (empty($imgUrl)) {
            return [];
        }

        $background = explode('.com/', $imgUrl)[1];
        $dir = dirname(dirname(dirname(dirname(dirname(__FILE__))))).'/public/uploads/';
        $this->setDir($dir);
        //$imageBackground = $this->imgCircularHandle($background, false);                  //图片变圆处理

        $imageBackground = $this->radius_img($background,1);  //背景图

        //$imageBackground = $this->getImgResource($background,false);  //背景图
        $backgroundWide = imagesx($imageBackground);
        $backgroundHigh = imagesy($imageBackground);
        $image = $this->createImgDrawingBoard($backgroundWide, $backgroundHigh); //绘制图像资源
        //导入背景图
        $this->twoImgComposeHandle($image,$imageBackground,0,0,0,0,$backgroundWide,$backgroundHigh,$backgroundWide,$backgroundHigh);



        //展示图片导入【商品图】
        list($shWide,$shHigh) = [24,59];  //位置
        list($showWide,$showHigh) = [325,315]; //图大小
        //http://imagev3.dzxwbj.com/temp/20220929/22928c1a23d1d7aa1f9f99e4ab583aa5.png
        $showUrl = $dir.explode('.com/', $cover)[1];
        $showImage = $this->getImgResource($showUrl,true);
        if($showWide == imagesx($showImage)  &&  $showHigh == imagesy($showImage)) {
            $imageShowImg = $showImage;
        } else {
            $imageShowImg = $this->createImgDrawingBoard($showWide, $showHigh);
            $this->twoImgComposeHandle($imageShowImg,$showImage,0,0,0,0,$showWide,$showHigh,imagesx($showImage),imagesy($showImage));
        }
        $this->imageCopyHandle($image, $imageShowImg, $shWide, $shHigh, 0, 0, $showWide, $showHigh);

        //导入菊花码
        //http://imagev3.dzxwbj.com/temp/20220929/d2c7f63ad181cb18ffa4ac559c620a76.png
        $qrUrl = $dir.explode('.com/', $code_image)[1];
        $originalImageQr = $this->getImgResource($qrUrl,true);
        $originalQrWide = imagesx($originalImageQr);
        $originalQrHigh = imagesy($originalImageQr);

        list($qrWide,$qrHigh) = [82,82];
        list($qrCodeX,$qrCodeY) = [271,417];
        $imageQr= $this->createImgDrawingBoard($originalQrWide, $originalQrHigh);
        $this->twoImgComposeHandle($imageQr,$originalImageQr,0,0,0,0,$qrWide,$qrHigh,$originalQrWide,$originalQrHigh);
        $this->imageCopyHandle($image, $imageQr,$qrCodeX,$qrCodeY, 0,0, $qrWide, $qrHigh);

        //文字导入 --- 商品标题
        $name = '长按识别二维码';
        $this->setTypefaceImageColor($image,110,124,137);
        list($titleX,$titleY) = [267,525];
        $this->imageTtfTextHandle($image,10,0, $titleX,$titleY, $name);

        //门店
        //$storeName = '青柠茶室门店';
        $this->setTypefaceImageColor($image,225,225,225);
        $nameLen = strlen($storeName)/4 * 30 + ((strlen($storeName)/4 -1) *1);
        $titleX = $backgroundWide/2 - $nameLen/2;
        $titleY = 42;
        $this->imageTtfTextHandle($image,19,0, $titleX,$titleY, $storeName);

        //商品标题
        $shopName = $productModel->name;
        $this->setTypefaceImageColor($image,37,58,78);
        $title_size = 17;
        $title_row = 35; //行距
        $title_line_num = 9; //多少字换行
        list($titleX,$titleY) = [24,439];
        $shopNameLen =mb_strlen($shopName,'UTF8');
        if($shopNameLen > $title_line_num && $title_line_num > 0) { //进行换行处理
            $shopNameOne = mb_substr($shopName,0,$title_line_num,'UTF8');
            $shopNameTow = mb_substr($shopName,$title_line_num,$title_line_num,'UTF8');
            $this->imageTtfTextHandle($image,$title_size,0, $titleX,$titleY, $shopNameOne);
            $this->imageTtfTextHandle($image,$title_size,0, $titleX,$titleY+$title_row, $shopNameTow);
        }else {
            $this->imageTtfTextHandle($image,$title_size,0, $titleX,$titleY, $shopName);
        }

        //价格
        $price = '￥';
        $this->setTypefaceImageColor($image,243,93,81);
        list($titleX,$titleY) = [24,525];
        $this->imageTtfTextHandle($image,11,0, $titleX,$titleY, $price);
        $price = $productModel->price*1;
        $this->setTypefaceImageColor($image,243,93,81);
        list($titleX,$titleY) = [38,525];
        $this->imageTtfTextHandle($image,17,0, $titleX,$titleY, $price);

        $price = '原价¥'.$productModel->market_price*1;
        $this->setTypefaceImageColor($image,158,168,177);
        list($titleX,$titleY) = [85,525];
        $this->imageTtfTextHandle($image,11,0, $titleX,$titleY, $price);

        $catalogRoute = $this->getDir().'temp/share';
        $imgName = $productId.'_'.$productModel->store_id.'_'.time();
        $this->generateImageSave($image, $catalogRoute, $imgName);     //合成图片存储
        
        // https://csnum13.dzxwbj.com/uploads
        $url = 'https://csnum13.dzxwbj.com/uploads/temp/share/'.$imgName.'.png';
        //$url = explode('temp/', $imgUrl)[0].'temp/share/'.$imgName.'.png';
        return $url;
        //$this->imageDisplay($image);die;
    }
    

    /**
     * 设置文件读取目录
     * @param $dir
     */
    public function setDir($dir)
    {
        $this->fileDir = $dir;
    }

    /**
     * 获取文件决定路径
     * @return string
     */
    public function getDir()
    {
        if($this->fileDir) {
            return $this->fileDir;
        }
    }


    /**
     * 生成图片存储
     * @param $image
     */
    public function generateImageSave($image, $catalogRoute, $saveName = '')
    {
        //设置文件路径
        $saveName = ($saveName)? $saveName: time();
        $url = $catalogRoute.'/'.$saveName.'.png';//存储的路径

        //判断目录是否存在
        if (file_exists($catalogRoute) == false){
            //创建目录，并且设置最高权限
            if (!mkdir($catalogRoute, 0700, true)){
                return '目录创建失败';
            }
        }

        //imagejpeg($image,$url);  //生成jpg图片
        imagepng($image,$url);  //生成png图片
        imagedestroy($image);
        return $url;
    }

    /**
     * 图片变圆处理
     * @param $imgpath
     * @return resource
     */
    public function imgCircularHandle($imgPath, $type = false)
    {
        $imgPath = ($type)? $imgPath: $this->getDir().$imgPath;
        $ext = pathinfo($imgPath);
        $src_img = null;
        switch ($ext['extension']) {
            case 'jpg':
                $src_img = imagecreatefromjpeg($imgPath);
                break;
            case 'png':
                $src_img = imagecreatefrompng($imgPath);
                break;
        }
        $wh = getimagesize($imgPath);
        $w  = $wh[0];
        $h  = $wh[1];
        $w  = min($w, $h);
        $h  = $w;
        $img = imagecreatetruecolor($w, $h);
        imagesavealpha($img, true);//这一句一定要有
        $bg = imagecolorallocatealpha($img, 255, 255, 255, 127);//拾取一个完全透明的颜色,最后一个参数127为全透明
        imagefill($img, 0, 0, $bg);
        $r = $w / 2; //圆半径
        $y_x = $r; //圆心X坐标
        $y_y = $r; //圆心Y坐标
        for ($x = 0; $x < $w; $x++) {
            for ($y = 0; $y < $h; $y++) {
                $rgbColor = imagecolorat($src_img, $x, $y);
                if (((($x - $r) * ($x - $r) + ($y - $r) * ($y - $r)) < ($r * $r))) {
                    imagesetpixel($img, $x, $y, $rgbColor);
                }
            }
        }
        return $img;
    }


    /**
     * 图片写入文字处理
     * @param $image
     * @param $size
     * @param $angle
     * @param $x
     * @param $y
     * @param $text
     */
    public function imageTtfTextHandle($image, $size, $angle, $x, $y, $text)
    {
        $fontpath = dirname(__FILE__).'/msyh.ttc';
        imagettftext($image,$size, $angle, $x, $y, $this->getTypefaceImageColor(),$fontpath, $text);
    }

    /**
     * 设置图片文字颜色
     * @param $image
     * @param $red
     * @param $green
     * @param $blue
     */
    public function setTypefaceImageColor($image, $red, $green, $blue)
    {
        $this->typefaceColor = imagecolorallocate ($image, $red, $green, $blue);
    }

    /**
     * 获取图片文字颜色
     * @return int
     */
    public function getTypefaceImageColor() {
        if($this->typefaceColor) {
            return $this->typefaceColor;
        }
        return 0;
    }


    /**
     * 处理圆角图片
     * @param  string  $imgpath 源图片路径
     * @param  integer $radius  圆角半径长度默认为15,处理成圆型
     * @return [type]           [description]
     */
    public function radius_img($imgPath, $radius = 15 , $type = false) {
        $imgPath = ($type)? $imgPath: $this->getDir().$imgPath;
        $ext = pathinfo($imgPath);
        $src_img = null;
        switch ($ext['extension']) {
            case 'jpg':
                $src_img = imagecreatefromjpeg($imgPath);
                break;
            case 'png':
                $src_img = imagecreatefrompng($imgPath);
                break;
        }
        $wh = getimagesize($imgPath);
        $w  = $wh[0];
        $h  = $wh[1];
        // $radius = $radius == 0 ? (min($w, $h) / 2) : $radius;
        $img = imagecreatetruecolor($w, $h);
        //这一句一定要有
        imagesavealpha($img, true);
        //拾取一个完全透明的颜色,最后一个参数127为全透明
        $bg = imagecolorallocatealpha($img, 255, 255, 255, 127);
        imagefill($img, 0, 0, $bg);
        $r = $radius; //圆 角半径
        for ($x = 0; $x < $w; $x++) {
            for ($y = 0; $y < $h; $y++) {
                $rgbColor = imagecolorat($src_img, $x, $y);
                if (($x >= $radius && $x <= ($w - $radius)) || ($y >= $radius && $y <= ($h - $radius))) {
                    //不在四角的范围内,直接画
                    imagesetpixel($img, $x, $y, $rgbColor);
                } else {
                    //在四角的范围内选择画
                    //上左
                    $y_x = $r; //圆心X坐标
                    $y_y = $r; //圆心Y坐标
                    if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) {
                        imagesetpixel($img, $x, $y, $rgbColor);
                    }
                    //上右
                    $y_x = $w - $r; //圆心X坐标
                    $y_y = $r; //圆心Y坐标
                    if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) {
                        imagesetpixel($img, $x, $y, $rgbColor);
                    }
                    //下左
                    $y_x = $r; //圆心X坐标
                    $y_y = $h - $r; //圆心Y坐标
                    if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) {
                        imagesetpixel($img, $x, $y, $rgbColor);
                    }
                    //下右
                    $y_x = $w - $r; //圆心X坐标
                    $y_y = $h - $r; //圆心Y坐标
                    if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) {
                        imagesetpixel($img, $x, $y, $rgbColor);
                    }
                }
            }
        }
        return $img;
    }

    /**
     * 将图片绘制到画布处理
     */
    public function imageCopyHandle($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h)
    {
        imagecopy($dst_im, $src_im,  $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h);
        $this->imageDestroyHandle($src_im);
    }

    /**
     * 销毁创建出图像释放内存
     * @param $image
     */
    public function imageDestroyHandle($image)
    {
        imagedestroy($image);
    }

    /**
     * 合成图片浏览器展示
     * @param $image
     */
    public function imageDisplay($image)
    {
        header("Content-Type:image/jpeg");
        imagejpeg($image);
        imagedestroy($image);
    }

    /**
     * 两图合成处理
     * @param $mainImg
     * @param $deputyImg
     * @param $dst_x
     * @param $dst_y
     * @param $src_x
     * @param $src_y
     * @param $dst_w
     * @param $dst_h
     * @param $src_w
     * @param $src_h
     * @return mixed
     */
    public function twoImgComposeHandle($mainImg, $deputyImg, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h)
    {
        imagecopyresampled($mainImg,$deputyImg,$dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
        imagedestroy($deputyImg); //释放
    }

    /**
     * 创建图片画板
     * @param $width
     * @param $height
     * @return resource
     */
    public function createImgDrawingBoard($width, $height)
    {
        return imagecreatetruecolor($width, $height);
    }

    /**
     * 从给定的文件名取得的图像
     * @param $fileName
     * @return resource
     */
    public function getImgResource($fileName, $type = false)
    {
        $fileName = ($type)? $fileName: $this->getDir().$fileName;
        $info = getimagesize($fileName);
        //获取图片的后缀
        $type = image_type_to_extension($info[2], false);
        //拼接图片资源句柄函数
        $func = 'imagecreatefrom'.$type;
        return $func($fileName);
    }









}